<template>
<AdminFramework>
  <h1>编辑文章</h1>
  <el-form>
    <el-form-item label="标题">
      <el-input placeholder="请输入标题" v-model="editBlog.title" />
    </el-form-item>
  </el-form>
  <MarkdownEditor ref="editor" class="markdown-editor" :value="editBlog?.markdown" height="600px" />
  <el-button @click="submitBlogHandle" class="save-btn" type="primary">保存</el-button>
</AdminFramework>
</template>

<script setup>
import AdminFramework from "../../../components/admin/UiFramework/AdminFramework.vue";
import {useRoute, useRouter} from "vue-router";
import {onMounted, ref} from "vue";
import MarkdownEditor from "../../../components/markdown/MarkdownEditor.vue";
import axios from "axios";
import {ElNotification} from "element-plus";
import {request} from "../../../api/baseFentch";

const route = useRoute()
const router = useRouter()

const editBlog = ref({
  title: ''
})
const editor = ref()

const isEdit = route.query?.id !== undefined
const queryId = route.query?.id

const getBlog = async id => {
  const result = (await axios.get(`/api/blog/${id}`))?.data
  if (result?.code === 0) {
    editBlog.value = result?.object
    return
  }
  ElNotification.error({
    message: result?.message
  })
}

const updateBlog = async (id, title, md) => {
  let data = new FormData();
  data.append('title', title);
  data.append('markdown', md);
  return await request(`/blog/${id}`, 'PUT', data);
}

const saveBlog = async (title, md) => {
  let data = new FormData();
  data.append('title', title);
  data.append('markdown', md);
  return await request('/blog', 'POST', data);
}

const submitBlogHandle = async () => {
  let markdown = editor.value.getMarkdown();
  let data
  if (isEdit) {
    data = await updateBlog(queryId, editBlog.value.title, markdown)
  } else {
    data = await saveBlog(editBlog.value.title, markdown)
  }
  if (data?.code === 0) {
    await router.push(('/admin/blog'))
    return
  }
  ElNotification.error({
    message: data?.msg
  })
}

onMounted(async () => {
  // 对是否为编辑进行判断并获取数据
  if (isEdit) {
    await getBlog(queryId)
  }
})
</script>

<style scoped>
.save-btn {
  margin-top: 20px;
}
</style>